package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存访客数据
     *  需求：
     *    对于同一个用户的访客记录，一天只记录一条
     */
    public void save(Visitors visitors) {
        //1、判断访问人对被访问人，当日是否有访客记录 （userId,visitorUserId,visitDate）
        Criteria criteria = Criteria.where("userId").is(visitors.getUserId())
                .and("visitorUserId").is(visitors.getVisitorUserId())
                .and("visitDate").is(visitors.getVisitDate());
        Query query = Query.query(criteria);
        if(!mongoTemplate.exists(query,Visitors.class)) {
            //2、如果访客记录不存在，保存
            mongoTemplate.save(visitors);
        }
    }

    //根据用户id查询最新访客，查询5条
    public List<Visitors> findByUserId(Long userId, Long time) {
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("date").gt(time);
        Query query = Query.query(criteria).with(Sort.by(Sort.Order.desc("date")))
                .limit(5);
        return mongoTemplate.find(query,Visitors.class);
    }

    //分页查询访客数据
    public List<Visitors> findAll(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("date")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        return mongoTemplate.find(query,Visitors.class);
    }
}
